﻿Public Class frmIssueRoom

    Private sdt As DataTable
    Private cdt As DataTable

    Private deRoom As Long
    Private khrAmount As Long
    Private totalCoinAmount As Long
    Private m As Integer
    Private y As Integer
    Private action As String
    Private actType As String() = {"INSERT", "UPDATE"}
    Private fmclose As Boolean = True

    Private sda As New DSVaultingTableAdapters.ir_monthly_issue_sheet_stocksTableAdapter
    Private cda As New DSVaultingTableAdapters.ir_monthly_issue_coin_stocksTableAdapter

    Private sdda As New DSVaultingTableAdapters.ir_issue_sheet_stock_detailsTableAdapter
    Private cdda As New DSVaultingTableAdapters.ir_issue_coin_stock_detailsTableAdapter

    Private Sub frmReserveRoom_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        m = frmMonthYearPicker.uxMonthcbb.SelectedIndex
        y = Integer.Parse(frmMonthYearPicker.uxYearcbb.Text)
        deRoom = frmIssueRoomslc.uxRoomCbx.SelectedValue

        '
        ' Set label title
        '
        uxRRHeaderLbl.Text = "ឃ្លាំងបោះផ្សាយ " & frmIssueRoomslc.uxRoomCbx.Text & " (ខែ " & frmMonthYearPicker.getKHMonth(m) & " " & y & ")"

        If checkCurrentMonth() Then
            If frmLogin.UserRole = frmLogin.RoleAdmin Then
                action = actType(1)
            Else
                uxSheetDgv.Columns("NoteSack20").ReadOnly = True
                uxSheetDgv.Columns("NoteSack30").ReadOnly = True
                uxSheetDgv.Columns("RedPack").ReadOnly = True
                uxCoinDgv.Columns("SackTwenty").ReadOnly = True
                uxCoinDgv.Columns("GoodCoin").ReadOnly = True
                uxCoinDgv.Columns("OldCoin").ReadOnly = True
                uxSaveChangeBtn.Enabled = False
            End If

            sdt = sdda.GetDataByRelatedTable(deRoom, m, y)
            cdt = cdda.GetDataByRelatedTable(deRoom, m, y)

            khrAmount = sdt.Rows(0).Item("TOTAL_AMOUNT")
            uxKHRTotalTbx.Text = FormatNumber(khrAmount, 0)
            totalCoinAmount = cdt.Rows(0).Item("TOTAL_AMOUNT")
            uxCOINTotalTbx.Text = FormatNumber(totalCoinAmount, 0)

            updateTotalAmount()
        Else
            sdt = sda.GetDataBySeries
            cdt = cda.GetDataByCoinOnly

            If frmLogin.UserRole = frmLogin.RoleAdmin Or frmLogin.UserRole = frmLogin.RoleUser Then
                action = actType(0)
            Else
                uxSheetDgv.Columns("NoteSack20").ReadOnly = True
                uxSheetDgv.Columns("NoteSack30").ReadOnly = True
                uxSheetDgv.Columns("RedPack").ReadOnly = True
                uxCoinDgv.Columns("SackTwenty").ReadOnly = True
                uxCoinDgv.Columns("GoodCoin").ReadOnly = True
                uxCoinDgv.Columns("OldCoin").ReadOnly = True
                uxSaveChangeBtn.Enabled = False
            End If

            Dim i As Integer
            For i = 0 To sdt.Rows.Count - 1
                sdt.Rows(i)("room_id") = deRoom
                sdt.Rows(i)("stock_month") = m
                sdt.Rows(i)("stock_year") = y
            Next

            Dim x As Integer
            For x = 0 To cdt.Rows.Count - 1 Step 1
                cdt.Rows(x)("ROOM_ID") = deRoom
                cdt.Rows(x)("STOCK_MONTH") = m
                cdt.Rows(x)("STOCK_YEAR") = y
            Next
        End If

        uxSheetDgv.DataSource = sdt
        uxCoinDgv.DataSource = cdt
    End Sub

    Private Function updateNoteAmount(ByVal dgv As DataGridView, _
                                  ByVal fstCol As String, _
                                  ByVal sndCol As String, _
                                  ByVal thdCol As String, _
                                  ByVal fthCol As String, _
                                  ByVal fstSum As String, _
                                  ByVal sndSum As String, _
                                  ByVal sumall As String) As Long
        Dim sum As Long
        Dim sum1 As Long
        Dim sum2 As Long
        Dim total As Long = 0
        Dim val As Long
        Dim qt20 As Long
        Dim qtwhite As Long
        Dim qtRed As Long
        Dim i As Integer

        For i = 0 To dgv.Rows.Count - 1 Step 1
            Try
                val = If(IsNumeric(dgv.Rows(i).Cells(fstCol).Value), dgv.Rows(i).Cells(fstCol).Value, 0)
                qt20 = If(IsNumeric(dgv.Rows(i).Cells(sndCol).Value), dgv.Rows(i).Cells(sndCol).Value, 0)
                qtwhite = If(IsNumeric(dgv.Rows(i).Cells(thdCol).Value), dgv.Rows(i).Cells(thdCol).Value, 0)
                sum = ((qtwhite * 1000) + (qt20 * 20 * 1000)) * val

                qtRed = If(IsNumeric(dgv.Rows(i).Cells(fthCol).Value), dgv.Rows(i).Cells(fthCol).Value, 0)
                sum1 = (qtRed * 1000) * val
            Catch ex As Exception
                MsgBox("The value is too big!")
            End Try
            dgv.Rows(i).Cells(sndCol).Value = qt20
            dgv.Rows(i).Cells(thdCol).Value = qtwhite
            dgv.Rows(i).Cells(fthCol).Value = qtRed
            dgv.Rows(i).Cells(fstSum).Value = sum
            dgv.Rows(i).Cells(sndSum).Value = sum1
            sum2 = sum + sum1
            dgv.Rows(i).Cells(sumall).Value = sum2
            total += sum2
        Next
        dgv.Update()
        Return total
    End Function

    Private Sub txtEdit_Keypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If IsNumeric(e.KeyChar.ToString()) _
        Or e.KeyChar = ChrW(Keys.Back) Then
            e.Handled = False 'if numeric display
        Else
            e.Handled = True  'if non numeric don't display
        End If
    End Sub

    Private Sub uxSheetDgv_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs)
        Dim txtEdit As TextBox = e.Control
        'remove any existing handler
        RemoveHandler txtEdit.KeyPress, AddressOf txtEdit_Keypress
        AddHandler txtEdit.KeyPress, AddressOf txtEdit_Keypress
    End Sub

    Private Sub uxCoinDgv_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles uxCoinDgv.CellEndEdit
        totalCoinAmount = updateNoteAmount(uxCoinDgv, "CoinType", "SackTwenty", "GoodCoin", "OldCoin", "GoodCoinTotal", "TotalOldCoin", "TotalCoin")
        uxCOINTotalTbx.Text = FormatNumber(totalCoinAmount, 0)
    End Sub

    Private Sub uxCoinDgv_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles uxCoinDgv.EditingControlShowing
        uxSheetDgv_EditingControlShowing(sender, e)
    End Sub

    Private Sub updateTotalAmount()
        uxTotalTbx.Text = FormatNumber(khrAmount + totalCoinAmount, 0)
    End Sub

    Private Sub uxKHRTotalTbx_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxKHRTotalTbx.TextChanged
        updateTotalAmount()
    End Sub

    Private Sub uxCOINTotalTbx_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxCOINTotalTbx.TextChanged
        updateTotalAmount()
    End Sub

    Private Sub uxCancelBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxCancelBtn.Click
        fmclose = False
        If MsgBox("តើអ្នកពិតជាចង់ចាកចេញមែន រឺ ទេ?", MsgBoxStyle.YesNo) = DialogResult.Yes Then
            Me.Close()
            frmRoomSelecting.Enabled = True
        End If
    End Sub

    Private Sub uxSaveChangeBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxSaveChangeBtn.Click
        Dim sql As New ArrayList()

        Dim sheetStockDetail As String = "ir_issue_sheet_stock_details"
        Dim coinStockDetail As String = "ir_issue_coin_stock_details"
        Dim sheetStock As String = "ir_monthly_issue_sheet_stocks"
        Dim coinStock As String = "ir_monthly_issue_coin_stocks"

        If action = actType(0) Then ' DO INSERT
            Dim i As Integer
            Dim stockCoinID As Long = cda.ScalarQueryNewID
            Dim stockSheetID As Long = sda.ScalarQueryNewID
            '
            ' Insert statement for reserve_sheet_stock
            '
            sql.Add("INSERT INTO " & sheetStock & " VALUES (" & stockSheetID & _
                    "," & uxSheetDgv.Rows(0).Cells("ROOM_ID").Value & _
                    "," & khrAmount & _
                    "," & m & "," & y & ")")
            For i = 0 To uxSheetDgv.RowCount - 1 Step 1
                sql.Add("INSERT INTO " & sheetStockDetail & " VALUES (" & stockSheetID & _
                        "," & uxSheetDgv.Rows(i).Cells("sheet_id").Value & _
                        "," & uxSheetDgv.Rows(i).Cells("NoteSack20").Value & _
                        "," & uxSheetDgv.Rows(i).Cells("NoteSack30").Value & _
                        "," & uxSheetDgv.Rows(i).Cells("Amount").Value & _
                        "," & uxSheetDgv.Rows(i).Cells("RedPack").Value & _
                        "," & uxSheetDgv.Rows(i).Cells("TotalRedPack").Value & _
                        ",NOW())")
            Next

            '
            ' Insert statement for reserve_coin_stock
            '
            sql.Add("INSERT INTO " & coinStock & " VALUES (" & stockCoinID & _
                    "," & uxCoinDgv.Rows(0).Cells("RoomID").Value & _
                    "," & totalCoinAmount & _
                    "," & m & "," & y & ")")
            For i = 0 To uxCoinDgv.RowCount - 1 Step 1
                sql.Add("INSERT INTO " & coinStockDetail & " VALUES (" & stockCoinID & _
                        "," & uxCoinDgv.Rows(i).Cells("coin_id").Value & _
                        "," & uxCoinDgv.Rows(i).Cells("SackTwenty").Value & _
                        "," & uxCoinDgv.Rows(i).Cells("GoodCoin").Value & _
                        "," & uxCoinDgv.Rows(i).Cells("GoodCoinTotal").Value & _
                        "," & uxCoinDgv.Rows(i).Cells("OldCoin").Value & _
                        "," & uxCoinDgv.Rows(i).Cells("TotalOldCoin").Value & _
                        ",NOW())")
            Next

        ElseIf action = actType(1) Then ' DO UPDATE
            Dim i As Integer
            Dim stockCoinID As Long = cda.ScalarQueryIDByRelatedFields(deRoom, m, y)
            Dim stockSheetID As Long = sda.ScalarQueryIDByRelatedFields(deRoom, m, y)
            '
            ' Update statement for reserve_sheet_stock
            '
            sql.Add("UPDATE " & sheetStock & " SET " & _
                    " TOTAL_AMOUNT =" & khrAmount & _
                    " WHERE STOCK_ID=" & stockSheetID)

            sql.Add("DELETE FROM " & sheetStockDetail & " WHERE STOCK_ID=" & stockSheetID)

            For i = 0 To uxSheetDgv.RowCount - 1 Step 1
                sql.Add("INSERT INTO " & sheetStockDetail & " VALUES (" & stockSheetID & _
                        "," & uxSheetDgv.Rows(i).Cells("sheet_id").Value & _
                        "," & uxSheetDgv.Rows(i).Cells("NoteSack20").Value & _
                        "," & uxSheetDgv.Rows(i).Cells("NoteSack30").Value & _
                        "," & uxSheetDgv.Rows(i).Cells("Amount").Value & _
                        "," & uxSheetDgv.Rows(i).Cells("RedPack").Value & _
                        "," & uxSheetDgv.Rows(i).Cells("TotalRedPack").Value & _
                        ",NOW())")
            Next

            '
            ' Insert statement for reserve_coin_stock
            '
            sql.Add("UPDATE " & coinStock & " SET " & _
                    " TOTAL_AMOUNT =" & totalCoinAmount & _
                    " WHERE STOCK_ID=" & stockCoinID)

            sql.Add("DELETE FROM " & coinStockDetail & " WHERE STOCK_ID=" & stockCoinID)

            For i = 0 To uxCoinDgv.RowCount - 1 Step 1
                sql.Add("INSERT INTO " & coinStockDetail & " VALUES (" & stockCoinID & _
                        "," & uxCoinDgv.Rows(i).Cells("coin_id").Value & _
                        "," & uxCoinDgv.Rows(i).Cells("SackTwenty").Value & _
                        "," & uxCoinDgv.Rows(i).Cells("GoodCoin").Value & _
                        "," & uxCoinDgv.Rows(i).Cells("GoodCoinTotal").Value & _
                        "," & uxCoinDgv.Rows(i).Cells("OldCoin").Value & _
                        "," & uxCoinDgv.Rows(i).Cells("TotalOldCoin").Value & _
                        ",NOW())")
            Next
        End If

        'Dim lg As New LogGenerator
        'Dim st As String
        'For Each s As String In sql
        '    st += s & ";" & vbNewLine
        'Next
        'lg.writeLog(st)
        '
        ' Execute Batch Insert
        '
        If action = "" Then
            MsgBox("លោកអ្នកមិនមានសិទ្ធគ្រប់គ្រាន់ទេ!", MsgBoxStyle.Exclamation)
        Else
            If MsgBox("តើលោកអ្នកពិតជាចង់រក្សាទុកអ្វីដែលបានកែប្រែមែនទេ??", MsgBoxStyle.YesNo) = DialogResult.Yes Then
                If executeBatch(sql) Then
                    MsgBox("ទិន្នន័យត្រួវបានរក្សាទុក")
                Else
                    MsgBox(DbConnect.errMsg)
                End If
            End If
        End If

    End Sub

    '
    ' Checking data for current month
    ' If data exist return true Otherwise false
    '
    Private Function checkCurrentMonth() As Boolean
        Dim val As Integer
        val = sda.ScalarQuerySelectMY(m, y, deRoom)

        If Not val = 0 Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub frmIssueRoom_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If fmclose = True Then
            If MsgBox("តើអ្នកពិតជាចង់ចាកចេញមែន រឺ ទេ?", MsgBoxStyle.YesNo) = DialogResult.Yes Then
                e.Cancel = False
                frmRoomSelecting.Enabled = True
            Else
                e.Cancel = True
            End If
        End If
    End Sub

    Private Sub uxSheetDgv_CellEndEdit_1(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles uxSheetDgv.CellEndEdit
        khrAmount = updateNoteAmount(uxSheetDgv, "NoteType", "NoteSack20", "NoteSack30", "RedPack", "Amount", "TotalRedPack", "Total")
        uxKHRTotalTbx.Text = FormatNumber(khrAmount, 0)
    End Sub
End Class